<template>
  <div class="forum-page">
    <div class="container">
      <!-- 论坛头部 -->
      <div class="forum-header">
        <h1 class="forum-title">职聊论坛</h1>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="10" animated />
      </div>

      <!-- 论坛内容区 -->
      <div v-else class="forum-content">
        <!-- 板块列表 -->
        <div class="forum-boards">
          <h2 class="section-title">板块导航</h2>
          
          <div class="board-list">
            <div 
              v-for="board in boards" 
              :key="board.id" 
              class="board-card"
              @click="viewBoard(board.id)"
            >
              <div class="board-icon" :style="{ backgroundColor: board.color }">
                <el-icon><component :is="board.icon" /></el-icon>
              </div>
              
              <div class="board-info">
                <div class="board-name">
                  <h3>{{ board.name }}</h3>
                </div>
                <div class="board-desc">{{ board.description }}</div>
                
                <div class="board-meta">
                  <div class="latest-topic" v-if="board.latestTopic">
                    <span class="meta-label">最新：</span>
                    <el-link 
                      type="primary" 
                      :underline="false"
                      @click.stop="viewTopic(board.latestTopic.id)"
                    >
                      {{ board.latestTopic.title }}
                    </el-link>
                  </div>
                 
                </div>
              </div>
              
          
            </div>
          </div>
        </div>


        <!-- 最新帖子 -->
        <div class="latest-topics">
          <h2 class="section-title">最新动态</h2>
          
          <div class="topic-list">
            <div 
              v-for="topic in latestTopics" 
              :key="topic.id" 
              class="topic-card"
              @click="viewTopic(topic.id)"
            >
              <div class="topic-content">
                <h3 class="topic-title">{{ topic.title }}</h3>
                <div class="topic-excerpt">{{ topic.excerpt }}</div>
                <div class="topic-meta">
                  <div class="board-tag" :style="{ backgroundColor: topic.boardColor + '20', color: topic.boardColor }">
                    {{ topic.boardName }}
                  </div>
                  <div class="meta-item">
                    <el-icon><view /></el-icon>
                    <span>{{ topic.views }}次浏览</span>
                  </div>
                  <div class="meta-item">
                    <el-icon><chat-line-round /></el-icon>
                    <span>{{ topic.replies }}条回复</span>
                  </div>
                </div>
              </div>
              
              <div class="topic-info">
                <div class="author-avatar">
                  <img v-if="topic.author && topic.author.avatar" :src="getFullAvatarURL(topic.author.avatar)" :alt="topic.author.name">
                  <div class="avatar-placeholder" v-else>{{ topic.author && topic.author.name ? topic.author.name.substring(0, 1) : '?' }}</div>
                </div>
                <div class="topic-time">
                  <div class="time-icon">
                    <el-icon><timer /></el-icon>
                  </div>
                  <span>{{ topic.publishTime }}</span>
                </div>
              </div>
            </div>
          </div>
          
          <div class="forum-pagination">
            <el-pagination
              background
              layout="prev, pager, next"
              :total="totalTopics"
              :page-size="5"
              :current-page="currentPage"
              @current-change="handlePageChange"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { 
  Plus, 
  ChatRound, 
  ChatDotRound, 
  User,
  View,
  ChatLineRound,
  Timer,
  Briefcase,
  Coin,
  School,
  Reading,
  OfficeBuilding,
  Guide,
  ArrowRight
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getForumStats, getForumBoards, getHotTopics, getLatestTopics } from '@/api/forum'
import { formatDistanceToNow } from 'date-fns'
import { zhCN } from 'date-fns/locale'
import { getFullAvatarURL } from '@/utils/common'

const router = useRouter()
const loading = ref(true)

// 论坛统计数据
const stats = reactive({
  topicCount: 0,
  replyCount: 0,
  userCount: 0
})

// 板块数据
const boards = ref([])

// 热门话题
const hotTopics = ref([])

// 最新帖子
const latestTopics = ref([])

// 分页相关数据
const currentPage = ref(1)
const totalTopics = ref(0)

// 获取论坛数据
const fetchForumData = async () => {
  loading.value = true
  try {
    // 获取论坛统计数据
    const statsRes = await getForumStats()
    if (statsRes.code === 200) {
      stats.topicCount = statsRes.data.topicCount
      stats.replyCount = statsRes.data.replyCount
      stats.userCount = statsRes.data.userCount
    }
    
    // 获取板块数据
    const boardsRes = await getForumBoards()
    if (boardsRes.code === 200) {
      boards.value = boardsRes.data.map(board => {
        // 映射图标名称到组件
        const iconMapping = {
          'briefcase': 'Briefcase',
          'coin': 'Coin',
          'school': 'School',
          'reading': 'Reading',
          'office-building': 'OfficeBuilding',
          'guide': 'Guide'
        }
        
        return {
          ...board,
          icon: iconMapping[board.icon] || 'Briefcase'
        }
      })
    }
    
    // 获取热门话题
    const hotRes = await getHotTopics(3)
    if (hotRes.code === 200) {
      hotTopics.value = hotRes.data.map(topic => {
        // 确保topic.author不为null
        const author = topic.author || { name: '匿名用户', avatar: null }
        return {
          ...topic,
          publishTime: formatTime(topic.createTime),
          author
        }
      })
    }
    
    // 获取最新话题
    const latestRes = await getLatestTopics(currentPage.value, 5)
    if (latestRes.code === 200 && latestRes.data && latestRes.data.records) {
      latestTopics.value = latestRes.data.records.map(topic => {
        // 确保topic.author不为null
        const author = topic.author || { name: '匿名用户', avatar: null }
        return {
          ...topic,
          publishTime: formatTime(topic.createTime),
          author
        }
      })
      
      // 更新分页信息
      totalTopics.value = latestRes.data.total
    }
    
  } catch (error) {
    console.error('获取论坛数据失败', error)
    ElMessage.error('获取论坛数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return ''
  try {
    return formatDistanceToNow(new Date(timestamp), { addSuffix: true, locale: zhCN })
  } catch (error) {
    console.error('时间格式化错误', error)
    return ''
  }
}

// 创建新话题
const createTopic = () => {
  // 检查用户是否登录
  const token = localStorage.getItem('token')
  if (!token) {
    router.push({
      path: '/auth/login',
      query: { redirect: '/forum/create' }
    })
    return
  }
  
  router.push('/forum/create')
}

// 查看话题详情
const viewTopic = (topicId) => {
  router.push(`/forum/topics/${topicId}`)
}

// 查看板块
const viewBoard = (boardId) => {
  router.push(`/forum/boards/${boardId}`)
}

// 查看所有热门话题
const viewAllHotTopics = () => {
  router.push('/forum/hot')
}

// 处理分页变化
const handlePageChange = async (page) => {
  try {
    loading.value = true
    const res = await getLatestTopics(page, 5)
    if (res.code === 200) {
      latestTopics.value = res.data.records.map(topic => {
        // 确保topic.author不为null
        const author = topic.author || { name: '匿名用户', avatar: null }
        return {
          ...topic,
          publishTime: formatTime(topic.createTime),
          author
        }
      })
      currentPage.value = page
    }
  } catch (error) {
    console.error('获取分页数据失败', error)
    ElMessage.error('获取分页数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchForumData()
})
</script>

<style lang="scss" scoped>
@import '@/assets/styles/variables.css';

// 多行文本省略混合函数
@mixin multi-line-ellipsis($lines) {
  display: -webkit-box;
  -webkit-line-clamp: $lines;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.forum-page {
  padding: var(--spacing-xl) 0;
  background-color: var(--bg-light);
  min-height: calc(100vh - 60px);
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 var(--spacing-lg);
}

// 论坛头部
.forum-header {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--spacing-xl);
  background-color: white;
  border-radius: var(--border-radius);
  padding: var(--spacing-lg);
  box-shadow: var(--box-shadow-sm);
  
  .forum-title {
    font-size: 1.8rem;
    font-weight: 700;
    color: var(--text-primary);
    margin: 0;
    flex-basis: 100%;
    margin-bottom: var(--spacing-md);
    
    @media (min-width: 768px) {
      flex-basis: auto;
      margin-bottom: 0;
    }
  }
  
  .forum-stats {
    display: flex;
    gap: var(--spacing-lg);
    
    .stat-item {
      display: flex;
      align-items: center;
      
      .el-icon {
        margin-right: var(--spacing-xs);
        color: var(--color-primary);
      }
    }
  }
}

// 加载状态
.loading-container {
  padding: var(--spacing-xl);
  background-color: white;
  border-radius: var(--border-radius);
  box-shadow: var(--box-shadow-sm);
}

// 内容区通用样式
.section-title {
  font-size: 1.4rem;
  font-weight: 600;
  margin: 0 0 var(--spacing-lg);
  color: var(--text-primary);
  display: flex;
  align-items: center;
  
  &::before {
    content: '';
    display: inline-block;
    width: 4px;
    height: 20px;
    background-color: var(--color-primary);
    margin-right: var(--spacing-sm);
    border-radius: 2px;
  }
}

// 论坛内容区
.forum-content {
  .forum-boards, .hot-topics, .latest-topics {
    background-color: white;
    border-radius: var(--border-radius);
    padding: var(--spacing-lg);
    box-shadow: var(--box-shadow-sm);
    margin-bottom: var(--spacing-xl);
  }
}

// 板块列表
.board-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(500px, 1fr));
  gap: var(--spacing-md);
  
  @media (max-width: 768px) {
    grid-template-columns: 1fr;
  }
  
  .board-card {
    display: flex;
    border: 1px solid var(--border-color);
    border-radius: var(--border-radius);
    padding: var(--spacing-md);
    transition: all 0.3s;
    cursor: pointer;
    
    &:hover {
      transform: translateY(-3px);
      box-shadow: var(--box-shadow-md);
      border-color: var(--color-primary);
    }
    
    .board-icon {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 50px;
      height: 50px;
      border-radius: 10px;
      margin-right: var(--spacing-md);
      flex-shrink: 0;
      
      .el-icon {
        font-size: 24px;
        color: white;
      }
    }
    
    .board-info {
      flex-grow: 1;
      
      .board-name {
        display: flex;
        align-items: baseline;
        margin-bottom: var(--spacing-xs);
        
        h3 {
          font-size: 1.1rem;
          font-weight: 600;
          margin: 0;
          margin-right: var(--spacing-md);
          color: var(--text-primary);
        }
        
        .topic-count {
          font-size: 0.9rem;
          color: var(--text-secondary);
        }
      }
      
      .board-desc {
        font-size: 0.95rem;
        color: var(--text-secondary);
        margin-bottom: var(--spacing-sm);
      }
      
      .board-meta {
        display: flex;
        flex-wrap: wrap;
        gap: var(--spacing-md);
        font-size: 0.85rem;
        
        .meta-label {
          color: var(--text-light);
        }
        
        .moderator-name {
          color: var(--text-secondary);
        }
      }
    }
    
    .board-stats {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      min-width: 80px;
      border-left: 1px solid var(--border-color);
      padding-left: var(--spacing-md);
      margin-left: var(--spacing-md);
      
      .stat {
        text-align: center;
        margin-bottom: var(--spacing-xs);
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .stat-number {
          font-size: 1.1rem;
          font-weight: 600;
          color: var(--color-primary);
        }
        
        .stat-label {
          font-size: 0.85rem;
          color: var(--text-secondary);
        }
      }
    }
  }
}

// 话题列表通用样式
.topic-list {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-md);
  
  .topic-card {
    display: flex;
    border: 1px solid var(--border-color);
    border-radius: var(--border-radius);
    padding: var(--spacing-md);
    transition: all 0.3s;
    cursor: pointer;
    
    &:hover {
      transform: translateY(-3px);
      box-shadow: var(--box-shadow-md);
      border-color: var(--color-primary);
    }
    
    &.hot {
      background-color: #fff9f2;
      border-color: #ffe7c7;
    }
  }
}

// 热门话题卡片
.hot-topics {
  .topic-card {
    .topic-votes {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      min-width: 60px;
      margin-right: var(--spacing-md);
      
      .vote-count {
        font-size: 1.3rem;
        font-weight: 700;
        color: var(--color-success);
      }
      
      .vote-label {
        font-size: 0.8rem;
        color: var(--text-light);
      }
    }
    
    .topic-content {
      flex-grow: 1;
      
      .topic-title {
        font-size: 1.2rem;
        font-weight: 600;
        margin: 0 0 var(--spacing-xs);
        color: var(--text-primary);
      }
      
      .topic-excerpt {
        font-size: 0.95rem;
        color: var(--text-secondary);
        margin-bottom: var(--spacing-sm);
        @include multi-line-ellipsis(2);
      }
      
      .topic-meta {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        gap: var(--spacing-md);
        
        .board-tag {
          padding: 2px 8px;
          border-radius: 4px;
          font-size: 0.85rem;
          font-weight: 500;
        }
        
        .meta-item {
          display: flex;
          align-items: center;
          font-size: 0.85rem;
          color: var(--text-light);
          
          .el-icon {
            margin-right: var(--spacing-xs);
            font-size: 0.95rem;
          }
        }
      }
    }
    
    .topic-author {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      margin-left: var(--spacing-md);
      
      .author-avatar {
        width: 50px;
        height: 50px;
        border-radius: 50%;
        overflow: hidden;
        margin-bottom: var(--spacing-xs);
        
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
        
        .avatar-placeholder {
          width: 100%;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          background-color: var(--color-primary);
          color: white;
          font-size: 1.5rem;
          font-weight: 500;
        }
      }
      
      .author-info {
        text-align: center;
        
        .author-name {
          font-size: 0.9rem;
          font-weight: 500;
          margin-bottom: 2px;
          color: var(--text-primary);
        }
        
        .publish-time {
          font-size: 0.8rem;
          color: var(--text-light);
        }
      }
    }
  }
  
  .more-action {
    display: flex;
    justify-content: center;
    margin-top: var(--spacing-md);
  }
}

// 最新帖子样式
.latest-topics {
  .topic-card {
    .topic-content {
      flex-grow: 1;
      
      .topic-title {
        font-size: 1.1rem;
        font-weight: 600;
        margin: 0 0 var(--spacing-xs);
        color: var(--text-primary);
      }
      
      .topic-excerpt {
        font-size: 0.95rem;
        color: var(--text-secondary);
        margin-bottom: var(--spacing-sm);
        @include multi-line-ellipsis(1);
      }
      
      .topic-meta {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        gap: var(--spacing-md);
        
        .board-tag {
          padding: 2px 8px;
          border-radius: 4px;
          font-size: 0.85rem;
          font-weight: 500;
        }
        
        .meta-item {
          display: flex;
          align-items: center;
          font-size: 0.85rem;
          color: var(--text-light);
          
          .el-icon {
            margin-right: var(--spacing-xs);
            font-size: 0.95rem;
          }
        }
      }
    }
    
    .topic-info {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-left: var(--spacing-md);
      min-width: 80px;
      
      .author-avatar {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        overflow: hidden;
        margin-bottom: var(--spacing-sm);
        
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
        
        .avatar-placeholder {
          width: 100%;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          background-color: var(--color-primary);
          color: white;
          font-size: 1.5rem;
          font-weight: 500;
        }
      }
      
      .topic-time {
        display: flex;
        align-items: center;
        font-size: 0.85rem;
        color: var(--text-light);
        
        .time-icon {
          margin-right: 4px;
        }
      }
    }
  }
  
  .forum-pagination {
    display: flex;
    justify-content: center;
    margin-top: var(--spacing-lg);
  }
}

// 响应式调整
@media (max-width: 768px) {
  .forum-header {
    flex-direction: column;
    align-items: flex-start;
    
    .forum-title {
      margin-bottom: var(--spacing-md);
    }
    
    .forum-stats {
      margin-bottom: var(--spacing-md);
      flex-wrap: wrap;
      gap: var(--spacing-md);
    }
  }
  
  .board-card {
    flex-direction: column;
    
    .board-icon {
      margin-bottom: var(--spacing-sm);
    }
    
    .board-stats {
      flex-direction: row;
      justify-content: flex-start;
      width: 100%;
      border-left: none;
      border-top: 1px solid var(--border-color);
      padding-left: 0;
      padding-top: var(--spacing-sm);
      margin-left: 0;
      margin-top: var(--spacing-sm);
      
      .stat {
        margin-right: var(--spacing-lg);
        margin-bottom: 0;
      }
    }
  }
  
  .hot-topics {
    .topic-card {
      flex-direction: column;
      
      .topic-votes {
        flex-direction: row;
        justify-content: flex-start;
        margin-right: 0;
        margin-bottom: var(--spacing-sm);
        
        .vote-count {
          margin-right: var(--spacing-xs);
        }
      }
      
      .topic-author {
        flex-direction: row;
        justify-content: flex-start;
        margin-left: 0;
        margin-top: var(--spacing-sm);
        
        .author-avatar {
          margin-bottom: 0;
          margin-right: var(--spacing-sm);
        }
        
        .author-info {
          text-align: left;
        }
      }
    }
  }
  
  .latest-topics {
    .topic-card {
      flex-direction: column;
      
      .topic-info {
        flex-direction: row;
        justify-content: flex-start;
        margin-left: 0;
        margin-top: var(--spacing-sm);
        
        .author-avatar {
          margin-bottom: 0;
          margin-right: var(--spacing-sm);
        }
      }
    }
  }
}
</style> 